package net.asfun.jvalog.frame;

import static net.asfun.jvalog.common.log.logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jangod.template.LazyBindings;
import net.asfun.jangod.template.TemplateEngine;
import net.asfun.jvalog.common.DualCacher;
import net.asfun.jvalog.mvc.ModelAndView;
import net.asfun.jvalog.vo.Setting;
import net.asfun.jvalog.vo.Site;

public class CachableView implements ModelAndView{

	private String name;
	private Map<String, Object> model = new HashMap<String, Object>();
	final static TemplateEngine engine = new TemplateEngine();
	final static String root = "themes/";
	final static LazyBindings common = new LazyBindings();
	
	static {
		Map<String, String> lazies = new HashMap<String,String>();
		lazies.put("categories", "net.asfun.jvalog.util.AutoLoader.getCategories");
        lazies.put("comments", "net.asfun.jvalog.util.AutoLoader.getComments");
        lazies.put("blogroll", "net.asfun.jvalog.util.AutoLoader.getLinks");
        lazies.put("recentPosts", "net.asfun.jvalog.util.AutoLoader.getPosts");
        lazies.put("archives", "net.asfun.jvalog.util.AutoLoader.getArchives");
		common.config(lazies);
		reset();
	}
	
	public static void reset() {
		common.put("site", Site.getInstance());
		engine.setEngineBindings(common);
		String theme = Site.getInstance().getTheme();
		if ( Setting.WEB_ROOT.endsWith("/") ) {
			engine.getConfiguration().setWorkspace(Setting.WEB_ROOT + root + theme + "/");
		} else {
			engine.getConfiguration().setWorkspace(Setting.WEB_ROOT + "/" + root + theme + "/");
		}
		logger.info("*********************reset cachableView");
	}
	
	@Override
	public Map<String, Object> getModel() {
		return model;
	}
	
	@Override
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String html = engine.process(name, model);
		String path = (String) request.getAttribute(ReadCacheInterceptor.PATH_PARAM);
		DualCacher.put(path, html);
		response.getWriter().write(html);
	}

	@Override
	public void addObject(String key, Object value) {
		model.put(key, value);
	}
}
